{% extends 'article/base.html' %}
{% load staticfiles %}
{% block title %}manage courses{% endblock %}
{% block content %}
<div>
<div class="text-right"><a href="{% url 'course:create_course' %}"><button type="button" class="btn btn-primary">添加课程</button></a></div>
<table class="table table-hover" style="margin-top: 10px">
    <tr>
        <td>序号</td>
        <td>课程标题</td>
        <td>发布日期</td>
        <td>操作</td>
    </tr>
    {% for course in courses %}
    <tr id="{{ forloop.counter }}">
    <td>{{ forloop.counter }}</td>
    <td>{{ course.title }}</td>
    <td>{{ course.created|date:"Y-m-d" }}</td>
    <td><a name="edit" href="{% url 'course:list_lessons' course.id %}"><span class="glyphicon glyphicon-pencil"></span></a></td>
    <td><a name="delete" href="{% url 'course:delete_course' course.id %}"><span class="glyphicon glyphicon-trash"></span></a></td>
    </tr>
    {% endfor %}
</table>
</div>
    <script type="text/javascript" src='{% static "js/jquery.js" %}'></script>
    <script type="text/javascript">
        function getCookie(name) {
            var cookieValue = null;
            if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }

        $(document).ready(function() {
            var csrftoken = getCookie('csrftoken');
            function csrfSafeMethod(method) {
                return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
            }
            $.ajaxSetup({
                crossDomain: false, // obviates need for sameOrigin test
                beforeSend: function(xhr, settings) {
                    if (!csrfSafeMethod(settings.type)) {
                        xhr.setRequestHeader("X-CSRFToken", csrftoken);
                    }
                }
            });
            var onDelete = function(){
                alert("delete it?");
                $.post(this.href, function(data) {
                    if (data.result == "ok"){
                        window.location.reload();
                    } else {
                        alert("sth wrong");
                    }
                }).fail(function() {
                    alert("error");
                });
                return false;
            };
            $(".delete").click(onDelete);
        })
    </script>
{% endblock %}